package cn.orange.ch10_dynamicprogramming;

import java.util.List;

/**
 * LC139.单词拆分
 */
public class LC139 {
    public boolean wordBreak(String s, List<String> wordDict) {
        int n = s.length();
        //dp[i]:以i-1结尾的字符串s可以由wordDict中的单词拼出时dp[i]为true
        boolean[] dp = new boolean[n + 1];
        dp[0] = true;
        for (int i = 1; i <= n; i++) {
            for (String word : wordDict) {
                int l = word.length();
                if (i >= l && dp[i - l] && word.equals(s.substring(i - l, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[n];
    }

    public static void main(String[] args) {
        LC139 alg = new LC139();
        System.out.println(alg.wordBreak("leetcode", List.of("leet", "code")));
        System.out.println(alg.wordBreak("applepenapple", List.of("apple", "pen")));
    }
}
